package com.qf.shiro;

import com.qf.pojo.DtsAdmin;
import com.qf.pojo.DtsPermission;
import com.qf.service.DtsAdminService;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.bcrypt.BCryptPasswordEncoder;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class AdminAuthorizingRealm extends AuthorizingRealm {
    @Autowired
    DtsAdminService adminService;
    @Autowired
    DtsRoleService roleService;
    @Autowired
    DtsPermissionService permissionService;
    /**
     * 授权
     * @param principal the primary identifying principals of the AuthorizationInfo that should be retrieved.
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取角色id
        DtsAdmin admin = (DtsAdmin) principal.getPrimaryPrincipal();
        Integer[] roleIds = admin.getRoleIds();

        //查询用户对应的角色
        Set<String> roles =roleService.findRolesByIds(roleIds);
        info.setRoles(roles);
        //查询用户对象的权限
        Set<String> perms = permissionService.findPermsByIds(roleIds);
        info.setStringPermissions(perms);

        return info;
    }

    /**
     * 认证
     * @param token the authentication token containing the user's principal and credentials.
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
       //获取输入的用户名和密码
        String username = (String) token.getPrincipal();
        String password =  new String((char[])token.getCredentials());

        //根据用户名查询
        DtsAdmin admin = adminService.findByUsername(username);
        if (admin == null){
            throw new UnknownAccountException("未知的账户");
        }
        //检验密码
        //TODO
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(password,admin.getPassword())){
            throw new CredentialsException("密码错误");
        }
        //判断账户是否锁定
        if (admin.getDeleted()){
            throw new LockedAccountException("账户已锁定");
        }

        //创建返回值对象
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin,password,admin.getUsername());
        return authenticationInfo;
    }
}
